package com.project.easy.common.db.mybatisplus.core.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.project.easy.common.db.mybatisplus.core.handler.FullFieldValueHandler;
import  com.project.easy.common.util.string.StringUtil;
import com.project.easyt.common.db.common.core.spring.DynamicDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author GreatorMan.cool
 * @copyright: Copyright (c) 2020
 * @company: 扬起科技有限公司
 * @date 2021/9/14 23:04
 * @description:
 */
@Configuration
public class SqlSessionFactoryConfig {

    @Value("${yqkj.zysoft.db.aliasesPackage:com.yqkj.zysoft.generator.entity}")
    private String aliasesPackage;

    @Value("${yqkj.zysoft.db.mapperDir:classpath:mapper/*.xml}")
    private String mapperDir;

    @Autowired
    private FullFieldValueHandler fullFieldValueHandler;
    /**
     * 初始化
     * @param dynamicDataSource 数据源管理
     * @return 返回 SqlSessionFactory
     * @throws Exception 异常
     */
    @Bean
    @ConditionalOnBean(DynamicDataSource.class)
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource dynamicDataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource);
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{getMybatisPlusInterceptorBean()});
        // 设置mybatis的主配置文件
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource mybatisConfigXml = resolver.getResource("classpath:mybatis/mybatis-config.xml");
        sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
        // 设置别名包
        sqlSessionFactoryBean.setTypeAliasesPackage(aliasesPackage);
        //手动配置mybatis的mapper.xml资源路径,如果单纯使用注解方式,不需要配置该行
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        //解析多个资源
        Resource[] result = getResources(resolver);

        sqlSessionFactoryBean.setMapperLocations(result);
        SqlSessionFactory object = sqlSessionFactoryBean.getObject();
        GlobalConfigUtils.getGlobalConfig(object.getConfiguration()).setMetaObjectHandler(fullFieldValueHandler);
        return object;
    }

    /**
     * 资源解析
     * @param resolver 资源解析器
     * @return 返回资源集合
     * @throws IOException IO文件异常
      */
    private Resource[] getResources(ResourcePatternResolver resolver) throws IOException {
        String[] resources = mapperDir.split(",");
        List<Resource> resourceList = new ArrayList<>();
        for (String resource: resources) {
            if (StringUtil.isNotBlank(resource)) {
                Resource[] resources1 = resolver.getResources(resource);
                if (Objects.nonNull(resources1) && resources1.length > 0) {
                    resourceList.addAll(Arrays.stream(resources1).collect(Collectors.toList()));
                }
            }
        }
        return resourceList.stream().toArray((Resource[]::new));
    }

    /**
     * 分页组件封装
     * @return 返回拦截器
     */
    public MybatisPlusInterceptor getMybatisPlusInterceptorBean() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
}
